package com.cheng.example.atguigu.view2.client41.chap2.v2;


import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 用Lock方式实现生产者消费模式
 */
class SharedData {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    private AtomicInteger atomicInteger=new AtomicInteger();
    private  volatile int number=0;
    private  int size=5;

    public void pro() {
        lock.lock();
        try {
            while (number >=size ) {
                condition.await();
            }
            atomicInteger.incrementAndGet();
            System.out.println(Thread.currentThread().getName() + "\t开始生产第： "+atomicInteger.get());
            number++;
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void cons() {
        lock.lock();
        try {
            while (number==0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "\t开始消费");
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}

public class ProConsLock {

    public static void main(String[] args) {
        SharedData sharedData = new SharedData();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                sharedData.pro();
            }
        }, "AAA").start();


//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                sharedData.cons();
            }
        }, "BBB").start();


    }
}
